<template>
  <div class="comment-item">
    <!-- 评论卡片 -->
    <div class="comment-card">
      <!-- 评论头部 -->
      <div class="comment-header">
        <div class="user-info">
          <div class="avatar">
            <el-avatar :size="40" :src="comment.avatarUrl">
              {{ comment.nickname.charAt(0) }}
            </el-avatar>
          </div>
          <div class="user-details">
            <div class="name-line">
              <span class="nickname" :class="{ 'is-author': comment.isAuthor }">
                {{ comment.nickname }}
              </span>
              <span v-if="comment.isAuthor" class="author-badge">博主</span>
              <span v-if="comment.isTop" class="top-badge">置顶</span>
            </div>
            <div class="meta">
              <span class="time" :title="comment.createTimeFormat">
                {{ comment.relativeTime || comment.createTimeFormat }}
              </span>
              <span v-if="comment.location" class="location">
                <el-icon>
                  <Location />
                </el-icon>
                {{ comment.location }}
              </span>
            </div>
          </div>
        </div>

        <div class="comment-actions">
          <el-button
            text
            size="small"
            :class="{ 'is-liked': comment.isLiked }"
            :loading="likingLoading"
            @click="toggleLike"
          >
            <el-icon>
              <transition name="like-fade" mode="out-in">
                <span :key="String(comment.isLiked)">
                  {{ comment.isLiked ? '👎' : '👍' }}
                </span>
              </transition>
            </el-icon>
            <span style="margin-left: 4px">{{ comment.likeCount || 0 }}</span>
          </el-button>

          <el-button v-if="comment.canReply" text size="small" @click="showReplyForm">
            <el-icon>
              <ChatDotRound />
            </el-icon>
            回复
          </el-button>
        </div>
      </div>

      <!-- 评论内容 -->
      <div class="comment-content">
        <div class="content-text" v-html="formatContent(comment.content)"></div>

        <!-- 回复表单 -->
        <div v-if="showReply" class="reply-form">
          <CommentForm
            :blog-id="blogId"
            :parent-id="comment.id"
            :reply-to-user-id="comment.replyToUserId"
            :reply-to-nickname="comment.nickname"
            :placeholder="`回复 @${comment.nickname}`"
            compact
            @comment-submitted="handleReplySubmitted"
            @cancel="() => emit('show-reply', null)"
          />
        </div>

        <!-- 回复列表 -->
        <div v-if="comment.children && comment.children.length > 0" class="replies-section">
          <div class="replies-header">
            <span class="replies-count">{{ comment.childrenTotal }} 条回复</span>
            <el-button text size="small" style="margin-left: 8px" @click="toggleReplies">
              {{ showReplies ? '收起回复' : '展开回复' }}
            </el-button>
          </div>
          <div v-if="showReplies">
            <div class="replies-list">
              <div v-for="reply in comment.children" :key="reply.id" class="reply-item">
                <div class="reply-header">
                  <span class="reply-nickname">
                    {{ reply.nickname }}
                    <span v-if="reply.isAuthor" class="author-badge">博主</span>
                  </span>
                  <span v-if="reply.replyToNickname" class="reply-to">
                    回复 @{{ reply.replyToNickname }}
                  </span>
                </div>
                <div class="reply-content" v-html="formatContent(reply.content)"></div>
                <div class="reply-meta">
                  <span class="reply-time">{{ reply.relativeTime || reply.createTimeFormat }}</span>
                  <div class="reply-actions">
                    <el-button
                      text
                      size="small"
                      :class="{ 'is-liked': reply.isLiked }"
                      @click="() => handleReplyLike(reply)"
                    >
                      <el-icon>
                        <transition name="like-fade" mode="out-in">
                          <span :key="String(reply.isLiked)">
                            {{ reply.isLiked ? '👎' : '👍' }}
                          </span>
                        </transition>
                      </el-icon>
                      <span style="margin-left: 4px">{{ reply.likeCount || 0 }}</span>
                    </el-button>
                    <el-button
                      v-if="reply.canReply"
                      text
                      size="small"
                      @click="() => handleReplyToReply(reply)"
                    >
                      <el-icon>
                        <ChatDotRound />
                      </el-icon>
                      回复
                    </el-button>
                  </div>
                </div>

                <!-- 回复的回复表单 -->
                <div v-if="activeNestedReplyId === reply.id" class="nested-reply-form">
                  <CommentForm
                    :blog-id="blogId"
                    :parent-id="comment.id"
                    :reply-to-user-id="reply.replyToUserId"
                    :reply-to-nickname="reply.nickname"
                    :placeholder="`回复 @${reply.nickname}`"
                    compact
                    @comment-submitted="handleReplySubmitted"
                    @cancel="() => emit('show-reply', null)"
                  />
                </div>
              </div>
            </div>
            <div
              v-if="comment.hasMore && comment.childrenTotal && comment.children"
              class="load-more-replies"
            >
              <el-button
                text
                size="small"
                :loading="loadingMoreReplies"
                @click="handleLoadMoreReplies"
              >
                加载更多回复 ({{ comment.childrenTotal - comment.children.length }})
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import { ChatDotRound, Location } from '@element-plus/icons-vue'
  import type { Comment } from '@/types/comment'
  import CommentForm from './CommentForm.vue'
  import { likeComment } from '@/api/comment'

  // 扩展Comment类型，确保hasMore和childrenTotal是可选的
  interface ExtendedComment extends Comment {
    hasMore?: boolean
    childrenTotal?: number
  }

  const props = defineProps<{
    comment: ExtendedComment
    blogId: string
    activeReplyId?: string | null
  }>()

  const emit = defineEmits<{
    reply: [comment: ExtendedComment]
    like: [comment: ExtendedComment]
    'show-reply': [commentId: string | null]
    'load-more-replies': [parentId: string, offset: number]
  }>()

  const likingLoading = ref(false)
  const activeNestedReplyId = ref<string | null>(null)
  const loadingMoreReplies = ref(false)
  const showReplies = ref(false)

  // 计算当前评论是否显示回复框
  const showReply = computed(() => {
    return props.activeReplyId === props.comment.id
  })

  const showReplyForm = () => {
    // 如果当前回复框已经显示，则关闭它；否则显示当前回复框
    const newReplyId = showReply.value ? null : props.comment.id
    emit('show-reply', newReplyId)
  }

  const toggleLike = async () => {
    if (likingLoading.value) return

    likingLoading.value = true
    try {
      emit('like', props.comment)
    } finally {
      likingLoading.value = false
    }
  }

  const handleReplyLike = async (reply: ExtendedComment) => {
    try {
      const param = {
        commentId: reply.id,
        isLike: !reply.isLiked,
      }

      await likeComment(param)

      // 更新本地状态
      reply.isLiked = !reply.isLiked
      reply.likeCount += reply.isLiked ? 1 : -1

      ElMessage.success(reply.isLiked ? '点赞成功' : '取消点赞成功')
    } catch (error) {
      console.error('点赞操作失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  }

  const handleReplyToReply = (reply: ExtendedComment) => {
    // 如果当前回复框已经显示，则关闭它；否则显示当前回复框
    activeNestedReplyId.value = activeNestedReplyId.value === reply.id ? null : reply.id
  }

  const handleLoadMoreReplies = async () => {
    if (!props.comment.children) return

    loadingMoreReplies.value = true
    try {
      emit('load-more-replies', props.comment.id, props.comment.children.length)
    } finally {
      loadingMoreReplies.value = false
    }
  }

  const handleReplySubmitted = () => {
    emit('show-reply', null) // 关闭回复框
    activeNestedReplyId.value = null
    emit('reply', props.comment)
  }

  const formatContent = (content: string) => {
    // 简单的内容格式化，可以扩展支持更多格式
    return content
      .replace(/\n/g, '<br>')
      .replace(/@(\w+)/g, '<span class="mention">@$1</span>')
      .replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>')
  }

  const toggleReplies = () => {
    showReplies.value = !showReplies.value
  }
</script>

<style scoped>
  .comment-item {
    margin-bottom: 20px;
    transition: all 0.3s ease;
  }

  .comment-card {
    background: var(--bg-color, #ffffff);
    border-radius: 12px;
    border: 1px solid var(--border-color, #e4e7ed);
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    padding: 20px;
    position: relative;
  }

  .comment-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary-color, #409eff) 0%, #66b3ff 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .comment-card:hover {
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
    transform: translateY(-2px);
    border-color: var(--primary-color, #409eff);
  }

  .comment-card:hover::before {
    opacity: 1;
  }

  .comment-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 18px;
  }

  .user-info {
    display: flex;
    gap: 16px;
    flex: 1;
  }

  .avatar {
    flex-shrink: 0;
  }

  .avatar .el-avatar {
    border: 2px solid var(--border-color, #e4e7ed);
    transition: all 0.3s ease;
  }

  .comment-card:hover .avatar .el-avatar {
    border-color: var(--primary-color, #409eff);
  }

  .user-details {
    flex: 1;
    min-width: 0;
  }

  .name-line {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
    flex-wrap: wrap;
  }

  .nickname {
    font-weight: 600;
    color: var(--text-primary, #303133);
    font-size: 16px;
    transition: color 0.3s ease;
  }

  .nickname.is-author {
    color: var(--primary-color, #409eff);
  }

  .author-badge {
    background: linear-gradient(135deg, var(--primary-color, #409eff), #66b3ff);
    color: white;
    font-size: 11px;
    padding: 3px 10px;
    border-radius: 14px;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
  }

  .top-badge {
    background: linear-gradient(135deg, #f56c6c, #ff8a8a);
    color: white;
    font-size: 11px;
    padding: 3px 10px;
    border-radius: 14px;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 4px rgba(245, 108, 108, 0.2);
  }

  .meta {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    color: var(--text-secondary, #909399);
    font-size: 13px;
  }

  .time {
    font-weight: 500;
  }

  .location {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .comment-actions {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .comment-actions .el-button {
    padding: 8px 16px;
    font-size: 13px;
    border-radius: 20px;
    transition: all 0.3s ease;
    font-weight: 500;
    border: 1px solid var(--border-color, #e4e7ed);
    background: var(--bg-secondary, #f8f9fa);
  }

  .comment-actions .el-button:hover {
    background: var(--primary-color, #409eff);
    border-color: var(--primary-color, #409eff);
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
  }

  .comment-actions .el-button.is-liked {
    background: linear-gradient(135deg, #f56c6c, #ff8080);
    border-color: #f56c6c;
    color: white;
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
  }

  .comment-content {
    padding: 0 4px;
  }

  .content-text {
    color: var(--text-primary, #606266);
    line-height: 1.7;
    margin-bottom: 16px;
    font-size: 15px;
    word-break: break-word;
  }

  .content-text :deep(.mention) {
    color: var(--primary-color, #409eff);
    font-weight: 600;
    background: rgba(64, 158, 255, 0.1);
    padding: 2px 6px;
    border-radius: 4px;
    transition: all 0.3s ease;
  }

  .content-text :deep(.mention:hover) {
    background: rgba(64, 158, 255, 0.2);
  }

  .content-text :deep(a) {
    color: var(--primary-color, #409eff);
    text-decoration: none;
    border-bottom: 1px dashed var(--primary-color, #409eff);
    transition: all 0.3s ease;
  }

  .content-text :deep(a:hover) {
    background: rgba(64, 158, 255, 0.1);
    border-bottom-style: solid;
  }

  .reply-form {
    margin-top: 18px;
    padding-top: 18px;
    border-top: 1px solid var(--border-color, #f0f2f5);
  }

  .replies-section {
    margin-top: 18px;
    padding-top: 18px;
    border-top: 1px solid var(--border-color, #f0f2f5);
  }

  .replies-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .replies-count {
    background: var(--bg-secondary, #f8f9fa);
    color: var(--text-secondary, #6b7280);
    font-size: 13px;
    padding: 6px 14px;
    border-radius: 18px;
    font-weight: 500;
    border: 1px solid var(--border-color, #e4e7ed);
  }

  .replies-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .reply-item {
    background: var(--bg-secondary, #f8f9fa);
    border-radius: 10px;
    padding: 16px;
    border: 1px solid var(--border-color, #f0f2f5);
    transition: all 0.3s ease;
    position: relative;
  }

  .reply-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(135deg, var(--primary-color, #409eff), #66b3ff);
    border-radius: 2px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  .reply-item:hover {
    background: rgba(64, 158, 255, 0.02);
    border-color: var(--primary-color, #409eff);
    transform: translateX(4px);
  }

  .reply-item:hover::before {
    opacity: 1;
  }

  .reply-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
  }

  .reply-nickname {
    font-weight: 600;
    color: var(--text-primary, #303133);
    font-size: 14px;
  }

  .reply-to {
    color: var(--primary-color, #409eff);
    font-size: 13px;
    font-weight: 500;
  }

  .reply-content {
    color: var(--text-primary, #606266);
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 12px;
  }

  .reply-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .reply-time {
    color: var(--text-secondary, #909399);
    font-size: 12px;
    font-weight: 500;
  }

  .reply-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .reply-actions .el-button {
    padding: 4px 12px;
    font-size: 12px;
    border-radius: 16px;
    transition: all 0.3s ease;
    font-weight: 500;
    border: 1px solid var(--border-color, #e4e7ed);
    background: var(--bg-color, #ffffff);
    color: var(--text-primary, #303133);
  }

  .reply-actions .el-button:hover {
    background: var(--primary-color, #409eff);
    border-color: var(--primary-color, #409eff);
    color: white;
    transform: translateY(-1px);
  }

  .nested-reply-form {
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid var(--border-color, #f0f0f0);
  }

  .load-more-replies {
    text-align: center;
    margin-top: 16px;
    padding: 12px 0;
    border-top: 1px dashed var(--border-color, #e4e7ed);
  }

  .load-more-replies .el-button {
    color: var(--primary-color, #409eff);
    font-size: 13px;
    font-weight: 500;
    border-radius: 16px;
    padding: 8px 16px;
    transition: all 0.3s ease;
  }

  .load-more-replies .el-button:hover {
    background: var(--primary-color, #409eff);
    color: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
  }

  /* 响应式调整 */
  @media (max-width: 768px) {
    .comment-card {
      padding: 16px;
    }

    .comment-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }

    .user-info {
      gap: 12px;
    }

    .comment-actions {
      margin-top: 8px;
      align-self: flex-start;
    }

    .reply-item {
      padding: 12px;
    }
  }

  /* 点赞切换动画 */
  .like-fade-enter-active,
  .like-fade-leave-active {
    transition:
      opacity 0.3s,
      transform 0.3s;
  }
  .like-fade-enter-from,
  .like-fade-leave-to {
    opacity: 0;
    transform: scale(0.6) rotate(-30deg);
  }
  .like-fade-leave-from,
  .like-fade-enter-to {
    opacity: 1;
    transform: scale(1) rotate(0);
  }
</style>
